package com.egglazy.Controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.egglazy.Service.WxUserService;
import com.egglazy.Utils.Result;
import com.egglazy.Utils.ResultUtil;
import com.egglazy.Utils.WebClientUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信用户接口")
@RestController
@RequestMapping("/wxUser")
public class WxUserController {

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Value("${wx.openid.url}")
    private String openIdUrl;

    private final WxUserService wxUserService;
    public WxUserController(WxUserService wxUserService) {
        this.wxUserService = wxUserService;
    }


    @Operation(summary = "通过code获取用户openId")
    @GetMapping("/getOpenIdByCode")
    public Result<Map<String, String>> getOpenIdByCode(@RequestParam("code") String code) {
        Map<String, String> params = new HashMap<>();
        params.put("secret", appSecret);
        params.put("appid", appId);
        params.put("code", code);
        params.put("grant_type", "authorization_code");

        String res = WebClientUtil.get(openIdUrl, params, String.class).block();
        if (res != null && !res.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(res);
            String openid = jsonObject.getString("openid");

            Map<String, String> map = new HashMap<>();
            map.put("openid", openid);
            return ResultUtil.success(map);
        }
        return ResultUtil.fail("获取openId失败！");
    }




}
